package com.jml.zlhq.app.widgets;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Scroller;

import com.jml.zlhq.app.R;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.UIUtil;
/**
 * 窗帘拉开自定义布局
 */
public class CurtainView extends RelativeLayout implements OnTouchListener{
	private Context mContext;
	/** Scroller 拖动类 */
	private Scroller mScroller;
	/** 屏幕高度  */
	private int mScreenHeigh = 0;
	/** 屏幕宽度  */
	private int mScreenWidth = 0;
	/** 点击时候Y的坐标*/
	private int downY = 0;
	/** 拖动时候Y的坐标*/
	private int moveY = 0;
	/** 拖动时候Y的方向距离*/
	private int scrollY = 0;
	/** 松开时候Y的坐标*/
	private int upY = 0;
	/** 广告幕布的高度*/
	private int curtainHeigh = 0;
	/** 是否 打开*/
	private boolean isOpen = false;
	/** 是否在动画 */
	private boolean isMove = false;
	/** 绳子的图片*/
	private LinearLayout header, content;
	/** 动画时间 */
	private int durateTime = 600;
	/** 其他空间高度 */
	private int barHight = 0;
	private final static int partOfView = 4;
	private final static int wucha = 0;
		
	public CurtainView(Context context) {
		super(context);
		init(context);
	}

	public CurtainView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		readAttrs(context, attrs);
		init(context);
	}

	public CurtainView(Context context, AttributeSet attrs) {
		super(context, attrs);
		readAttrs(context, attrs);
		init(context);
	}
	
	private void readAttrs(Context context, AttributeSet attrs) { 
        TypedArray types = context.obtainStyledAttributes(attrs,R.styleable.curtain); 
        final int count = types.getIndexCount(); 
        for (int i = 0; i < count; ++i) { 
            int attr = types.getIndex(i); 
            switch (attr) { 
            case R.styleable.curtain_barHight: 
            	barHight = types.getInt(attr, 0); 
                break; 
            case R.styleable.curtain_durateTime: 
            	durateTime = types.getInt(attr, 600); 
                break; 
            } 
        } 
        types.recycle(); 
    } 
	
	/** 初始化 */
	private void init(Context context) {
		this.mContext = context;
		//Interpolator 设置为有反弹效果的  （Bounce：反弹）
		mScroller = new Scroller(context);
		mScreenHeigh = BaseTools.getWindowHeigh(context);
		mScreenWidth = BaseTools.getWindowWidth(context);
		// 背景设置成透明
		this.setBackgroundColor(Color.argb(0, 0, 0, 0));
		int layout_curtain = R.layout.curtain;
		final View view = LayoutInflater.from(mContext).inflate(layout_curtain, null);
		content = (LinearLayout)view.findViewById(R.id.ct_view_content);
		header = (LinearLayout)view.findViewById(R.id.ct_view_header);
		header.setLayoutParams(new LinearLayout.LayoutParams(mScreenWidth, LayoutParams.WRAP_CONTENT));
		content.setLayoutParams(new LinearLayout.LayoutParams(mScreenWidth, LayoutParams.MATCH_PARENT));
		
		addView(view);
		content.post(new Runnable() {
			
			@Override
			public void run() {
				curtainHeigh  = header.getHeight()-(mScreenHeigh-UIUtil.dip2px(mContext,barHight)-UIUtil.getStatusBarHeight(mContext));
				LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,Math.abs(mScreenHeigh-curtainHeigh));
				content.setLayoutParams(lp);
				CurtainView.this.scrollTo(0, curtainHeigh);
				isOpen = false;
				//注意scrollBy和scrollTo的区别
			}
		});
		header.setOnTouchListener(this);
		content.setOnTouchListener(this);
		
		//TODO
		//playerView(header);
		//header.layout(0, (mScreenHeigh-UIUtil.getStatusBarHeight(mContext))/2, mScreenWidth, (mScreenHeigh-UIUtil.getStatusBarHeight(mContext))/2+header.getHeight());

	}

	/**
	 * 拖动动画
	 * @param startY  
	 * @param dy  垂直距离, 滚动的y距离
	 * @param duration 时间
	 */
	public void startMoveAnim(int startY, int dy, int duration) {
		isMove = true;
		mScroller.startScroll(0, startY, 0, dy, duration);
		invalidate();//通知UI线程的更新
	}
	
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);
	}
	
	@Override
	public void computeScroll() {
		//判断是否还在滚动，还在滚动为true
		if (mScroller.computeScrollOffset()) {
			scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
			header.layout(0, (int)(mScreenHeigh+mScroller.getCurrY()-header.getHeight()-UIUtil.getStatusBarHeight(mContext)), mScreenWidth, (int)(mScreenHeigh+mScroller.getCurrY()-UIUtil.getStatusBarHeight(mContext)));
			//更新界面
			postInvalidate();
			isMove = true;
		} else {
			isMove = false;
		}
		super.computeScroll();
	}

	@Override
	@SuppressLint("ClickableViewAccessibility")
	public boolean onTouch(View v, MotionEvent event) {
		if (!isMove) {
			@SuppressWarnings("unused")
			int offViewY = 0;//屏幕顶部和该布局顶部的距离
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				downY = (int) event.getRawY();
				offViewY = downY - (int)event.getX();
				return true;
			case MotionEvent.ACTION_MOVE:
				moveY = (int) event.getRawY();
				scrollY = moveY - downY;
				if (scrollY < 0) {
					// 向上滑动
					if(!isOpen){
						if(Math.abs(scrollY) <= Math.abs(curtainHeigh)){
							scrollTo(0, curtainHeigh-scrollY);
							header.layout(0, Math.abs(scrollY), mScreenWidth, Math.abs(scrollY)+header.getHeight());
					}
					}
				} else {
					// 向下滑动
					if(isOpen){
						if (scrollY <= -curtainHeigh) {
							scrollTo(0, -scrollY);
							header.layout(0, mScreenHeigh-scrollY-header.getHeight()-UIUtil.getStatusBarHeight(mContext), mScreenWidth, mScreenHeigh-scrollY-UIUtil.getStatusBarHeight(mContext));
						}
					}
				}
				break;
			case MotionEvent.ACTION_UP:
				upY = (int) event.getRawY();
				if(Math.abs(upY - downY) < 10){
					//onRopeClick();
					break;
				}
				if (downY > upY) {
					// 向上滑动
					if (Math.abs(scrollY) > Math.abs(curtainHeigh) / partOfView) {
						// 向上滑动超过半个屏幕高的时候 开启向上消失动画
						startMoveAnim(this.getScrollY(), -this.getScrollY()+wucha, durateTime);
						isOpen = true;
					} else {
						startMoveAnim(this.getScrollY(), (curtainHeigh-this.getScrollY()),durateTime);
						isOpen = false;
					}
					
				} else {
					// 向下滑动
					if(isOpen){
						if (Math.abs(scrollY) > Math.abs(curtainHeigh) / partOfView) {
							// 向上滑动超过半个屏幕高的时候 开启向上消失动画
							startMoveAnim(this.getScrollY(), (curtainHeigh-this.getScrollY()),durateTime);
							isOpen = false;
						} else {
							startMoveAnim(this.getScrollY(),-this.getScrollY()+wucha, durateTime);
							isOpen = true;
						}
					}
				}
				onFinishMove();
				break;
			default:
				break;
			}
		}
		return false;
	}
	/**
	 * 点击绳索开关，会展开关闭
	 * 在onToch中使用这个中的方法来当点击事件，避免了点击时候响应onTouch的衔接不完美的影响
	 */
	public void onRopeClick(){
		if(isOpen){
			CurtainView.this.startMoveAnim(0, curtainHeigh, durateTime);
		}else{
			CurtainView.this.startMoveAnim(curtainHeigh,-curtainHeigh, durateTime);
		}
		isOpen = !isOpen;
		onFinishMove();
	}
	
	@SuppressLint("ResourceAsColor")
	private void onFinishMove(){
		header.setBackgroundColor(R.color.blue);
		LinearLayout.LayoutParams ll =new LinearLayout.LayoutParams(mScreenWidth, UIUtil.dip2px(mContext, 60));
		ll.setMargins(0, 0, 0, 0);
	}
}
